package ru.susu.algebra.util;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import com.google.common.base.Function;
import com.google.common.collect.Collections2;
import com.google.common.collect.Lists;

import ru.susu.algebra.pair.Pair;

/**
 * @author akargapolov
 * @since: 16.08.2010
 */
public class CollectionUtils
{
	public static <T> Collection<T> removeNulls(Collection<T> unfiltered)
	{
		return Collections2.filter(unfiltered, Predicates.getNotNullPredicate());
	}

	public static <K,V> Collection<V> getValues(Collection<Pair<K,V>> collection)
	{
		return Collections2.transform(collection, new Function<Pair<K,V>, V>()
		{
			@Override
			public V apply(Pair<K, V> pair)
			{
				return pair.getValue();
			}
		});
	}

	public static <K,V> Collection<V> getKeys(Collection<Pair<K,V>> collection)
	{
		return Collections2.transform(collection, new Pair.KeyFunction<V>());
	}

	public static <T> List<T> sort(List<T> source, boolean createNewCopy, Comparator cmp)
	{
		if (createNewCopy)
		{
			List<T> result = new ArrayList<T>();
			result.addAll(source);
			Collections.sort(result, cmp);
			return result;
		}
		Collections.sort(source, cmp);
		return source;
	}

	public static <T> String toString(Collection<T> collection, String delimeter)
	{
		StringBuffer buffer = new StringBuffer();
		for (T obj : collection)
		{
			buffer = buffer.length() == 0 ? buffer : buffer.append(delimeter);
			buffer.append(obj);
		}
		return buffer.toString();
	}

	public static <T> List<Collection<T>> split(Collection<T> collection, int partSize)
	{
		List<Collection<T>> result = Lists.newArrayList();
		List<T> part = Lists.newArrayList();
		for (T obj : collection)
		{
			part.add(obj);
			if (part.size() >= partSize)
			{
				result.add(part);
				part = Lists.newArrayList();
			}
		}
		if (!part.isEmpty())
		{
			result.add(part);
		}
		return result;
	}
}
